﻿using System;
using System.IO;
using System.Management;
using System.Security.Cryptography;
using System.Text;

namespace eShop.Core
{
    /// <summary>
    /// RSA非对称加密算法
    /// </summary>
    public class RSApublic
    {
        /// <summary>
        /// 描述：公钥
        /// </summary>
        private static string publicKeyStr = @"<RSAKeyValue><Modulus>sJSNXb3+DSXdZ5raDgC7OaJ51NZMLxz2PeaVBQswYtwikQJlVYc+fXFFco1GKS5cnseumF4DSqcTCRf89GIOezvqTk3/MgG+820k2b6B+BvtTNnA41eKbd62proa2LlPlnwd9ldUA+sFnQePe7walN3DeCDjKVexNI1WwJVPyvE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

        /// <summary>
        /// 公钥验证签名
        /// </summary>
        /// <param name="sign">签名Str</param>
        /// <param name="validStr">需要验证的validStr</param>
        /// <returns></returns>
        public static bool varifySign(string sign, string validStr)
        {
            try
            {
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                byte[] signbytes = Convert.FromBase64String(sign);
                byte[] validStrbytes = Encoding.Unicode.GetBytes(validStr);
                rsa.FromXmlString(publicKeyStr);
                bool isVarify = false;
                isVarify = rsa.VerifyData(validStrbytes, new SHA1CryptoServiceProvider(), signbytes);
                return isVarify;
            }
            catch (Exception)
            {
                return false;
            }

        }


        /// <summary>
        /// 字符串解密
        /// </summary>
        /// <param name="sourceData"></param>
        /// <returns></returns>
        public static string longStringRSADescry(string sourceData)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] key = System.Text.Encoding.Default.GetBytes(publicKeyStr);    //加载公钥
            string privateKey = Encoding.ASCII.GetString(key);
            byte[] dataEnc = Convert.FromBase64String(sourceData);   //加载密文
            rsa.FromXmlString(privateKey);
            int keySize = rsa.KeySize / 8;
            byte[]
            buffer = new byte[keySize];

            MemoryStream msInput = new MemoryStream(dataEnc);
            MemoryStream msOutput = new MemoryStream();
            int readLen = msInput.Read(buffer, 0, keySize);
            while (readLen > 0)
            {
                byte[] dataToDec = new byte[readLen];
                Array.Copy(buffer, 0, dataToDec, 0, readLen);
                byte[] decData = rsa.Decrypt(dataToDec, false);
                msOutput.Write(decData, 0, decData.Length);
                readLen = msInput.Read(buffer, 0, keySize);
            }
            msInput.Close();
            byte[] result = msOutput.ToArray();
            //得到解密结果
            msOutput.Close();
            rsa.Clear();
            string returnStr = Encoding.ASCII.GetString(msOutput.ToArray());
            return returnStr;

        }
        /// <summary>
        /// 加密算法
        /// </summary>
        /// <param name="sourceData"></param>
        /// <returns></returns>
        public static string longStringRSAEncry(string sourceData)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] data = System.Text.Encoding.Default.GetBytes(sourceData);

            //要加密的数据
            string publicKey = publicKeyStr;  //获取公钥
            rsa.FromXmlString(publicKey);
            int keySize = rsa.KeySize / 8;
            int bufferSize = keySize - 11;
            byte[] buffer = new byte[bufferSize];

            MemoryStream msInput = new MemoryStream(data);
            MemoryStream msOutput = new MemoryStream();
            int readLen = msInput.Read(buffer, 0, bufferSize);

            while (readLen > 0)
            {
                byte[] dataToEnc = new byte[readLen];
                Array.Copy(buffer, 0, dataToEnc, 0, readLen);
                byte[] encData = rsa.Encrypt(dataToEnc, false);
                msOutput.Write(encData, 0, encData.Length);
                readLen = msInput.Read(buffer, 0, bufferSize);
            }
            msInput.Close();
            byte[] result = msOutput.ToArray();
            //得到加密结果
            msOutput.Close();
            rsa.Clear();
            string returnStr = Convert.ToBase64String(msOutput.ToArray());
            return returnStr;
        }

        #region 获取cpu序列号 硬盘ID 网卡硬地址
        /// <summary>
        /// 获取cpu序列号  
        /// </summary>
        /// <returns>string</returns>
        private static string GetCpuInfo()
        {
            string cpuInfo = "";
            ManagementClass cimobject = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = cimobject.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                try
                {
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                }
                catch
                {

                }
            }
            return cpuInfo.ToString();
        }

        /// <summary>
        /// 获取硬盘ID  
        /// </summary>
        /// <returns>string</returns>
        private static string GetHDid()
        {
            string HDid = "";
            ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
            ManagementObjectCollection moc1 = cimobject1.GetInstances();
            foreach (ManagementObject mo in moc1)
            {
                HDid = (string)mo.Properties["Model"].Value;
            }
            return HDid.ToString();
        }

        /// <summary>
        /// 获取网卡硬件地址
        /// </summary>
        /// <returns>string</returns>
        private static string GetMoAddress()
        {
            string MoAddress = "";
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc2 = mc.GetInstances();
            foreach (ManagementObject mo in moc2)
            {
                if ((bool)mo["IPEnabled"] == true)
                    MoAddress = mo["MacAddress"].ToString();
                mo.Dispose();
            }
            return MoAddress.ToString();
        }
        #endregion


        /// <summary>
        /// 得到注册码的有效期
        /// </summary>
        /// <param name="regCode"></param>
        /// <returns></returns>
        public static string GetExpiryDate(string regCode)
        {
            string[] matchArray = regCode.Split('|');
            string datetimeStr = "";
            if (matchArray.Length <= 1)
            {
                datetimeStr = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
            }
            else
            {
                datetimeStr = matchArray[1].ToString();
            }
            string decodeDateTimeStr = ZEncypt.DESDecrypt(datetimeStr);
            if (!ValidateHelper.IsDate(decodeDateTimeStr))
            {
                decodeDateTimeStr = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
            }
            return decodeDateTimeStr;
        }


        /// <summary>
        /// 取得机器码字符串
        /// </summary>
        /// <returns></returns>
        public static string GetMachineCode()
        {
            //string SourceCode = Encrypto(GetCpuInfo() + "|" + GetHDid() + "|" + GetMoAddress());//2009-7-13修改为下面一句
            string cpuInfo = "";
            string SourceCode = "";
            try
            {
                cpuInfo = GetCpuInfo();
                SourceCode += cpuInfo + "|";
            }
            catch
            {
            }
            try
            {
                SourceCode += GetHDid() + "|";
            }
            catch
            {
            }
            string moInfo = "";
            try
            {
                moInfo = GetMoAddress();
                SourceCode += moInfo + "|";
            }
            catch
            {

            }
            return SourceCode;
        }

    }
}
